import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
    const username = ref('')
    const cartList = ref([])
    const addItem = (payload) => {
        const index = cartList.value.findIndex(item => item.id == payload.id)
        if (index > -1) {
            cartList.value[index].count++
        } else {
            cartList.value.push({
                ...payload,
                count: 1,
                checked: false
            })
        }
    }
    const delel = (id) => {
        cartList.value = cartList.value.filter(item => item.id != id)
    }
    const totalPrice = computed(() => {
        let res = 0
        cartList.value.forEach(item => {
            if (item.checked === true) {
                res += item.price * item.count
            }
        })
        return res.toFixed(2)
    })
    const totalCount = computed(() => {
        let res = 0
        cartList.value.forEach(item => {
            res += item.count
        })
        return res
    })
    const orderList = computed(() => {
        return cartList.value.filter(item => item.checked == true)
    })

    return { username, cartList, totalPrice, totalCount, addItem, delel, orderList }
})